<%--
  @author Duminda Dharmakeerthi
  @author Supun Nimesh Karunathilaka
  @author Supun Viraj Rathnayaka
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="s" uri="/struts-tags" %>

<s:set name="usr" value="registerUser"/>
<script type="text/javascript">
$(document).ready(function () {
    /*
     $("#create-user").validate({
     rules: {
     checkUsername:{
     required: true
     },
     checkFullname:{
     required: true
     },
     checkEmail:{
     required: true,
     email:true
     },
     roleId:{
     selectBox:"default"
     },
     prefLanguage:{
     selectBox:"default"
     }
     //                dsDivision:{
     //                    selectBox:function(element){
     //                        alert(document.getElementById("id").value);
     //                       if(document.getElementById("id").value == "LO")
     //                       return "notdefault";
     //                   }
     //                }
     },
     messages: {
     checkUsername:{
     required:  "Please enter a username"
     },
     checkFullname:{
     required: "Please enter your full name"
     },
     checkEmail:{
     required:  "Please enter your email",
     email: "Please enter a valid email"
     },
     roleId:{
     selectBox:  "Please select the Role ID"
     },
     prefLanguage:{
     selectBox:  "Please select the Preferred Language"
     }
     //                dsDivision:{
     //                    selectBox: "Please Select a Ds Division"
     //                }
     }
     }); */


    showHideAddButton();

    $("#dsDivisionsSelected").each(function () {
        $("#dsDivisionsSelected option").attr("selected", "selected");
    });
    /*var count = document.getElementById("dsDivisionsSelected").options.length;
     document.getElementById("dsDivisionsSelectedTr").style.display = 'none';*/

    /*$("#userRolesSelected").each(function() {
     $("#userRolesSelected option").attr("selected", "selected");
     });*/
    /*var count = document.getElementById("userRolesSelected").options.length;
     document.getElementById("userRolesSelectedTr").style.display = 'none';*/

    var count = document.getElementById("dsDivisionsSelected").options.length;
//        var count1 = document.getElementById("userRolesSelected").options.length;
    var mode = document.getElementById("edit_mode").value;
    // var userRoleMode = document.getElementById("userRoleMode").value;
//    if (count == 0 || mode == 0 || isDSUser()) {
    document.getElementById("dsDivisionsSelectedTr").style.display = 'none';
//    }
    /* if(userRoleMode==1){
     $("#add").hide();
     } */
    /*if (count1 == 0 || mode == 0) {
     document.getElementById("userRolesSelectedTr").style.display = 'none';
     }*/

});

/*$(function () {*/
    /*var i=0;
     for( i=0;i<9;i++) {
     // alert("pro:");
     var options1 = '<option value="0"> - Select All - </option> ';
     //var dis = data.districtsList;
     //alert( i);
     for (var i = 0; i < i.length; i++) {
     options1 += '<option value="' + i + '">' + i + '</option>'

     }
     $("select#province").html(options1);
     }
     */


/*    $('select#province').bind('change', function (evt1) {
        var id = $("select#province").attr("value");
        //alert("PR:"+id);
        $.getJSON('${pageContext.request.contextPath}/common/DivisionLookupService', {id: id, mode: 1},
                function (data) {
                    //alert("ale:");
                    var options1 = '<option value="0"> - Select All - </option> ';
                    var dis = data.districtsList;
                    //alert( dis.length);
                    for (var i = 0; i < dis.length; i++) {
                        options1 += '<option value="' + dis[i].optionValue + '">' + dis[i].optionDisplay + '</option>'

                    }
                    $("select#district").html(options1);
                });

    });
});*/

$(function () {
    $('select#district').bind('change', function (evt1) {
        var id = $("select#district").attr("value");
        $.getJSON('${pageContext.request.contextPath}/common/DivisionLookupService', {id: id},
                function (data) {
                    var options1 = '<option value="0"> - Select All - </option> ';
                    var ds = data.dsDivisionList;
                    for (var i = 0; i < ds.length; i++) {
                        options1 += '<option value="' + ds[i].optionValue + '">' + ds[i].optionDisplay + '</option>'
                    }
                    $("select#dsDivision").html(options1);
                });

    });
});


function selectList() {
    $("#dsDivisionsSelected").each(function () {
        $("#dsDivisionsSelected option").attr("selected", "selected");
    });
}
function selectRolesList() {
    $("#userRolesSelected").each(function () {
        $("#userRolesSelected option").attr("selected", "selected");
    });
}

function addRow() {
    var dsDivisionName = $("#dsDivisionsSelected option:selected");
    dsDivisionName.each(function () {
        $("#dsDivisionsSelected option").remove();
    })
}

function removeOptionSelected() {
    var elSel = document.getElementById('dsDivisionsSelected');
    var i;
    for (i = elSel.length - 1; i >= 0; i--) {
        if (elSel.options[i].selected) {
            elSel.remove(i);
        }
    }
    var count = document.getElementById("dsDivisionsSelected").options.length;
    if (count == 0) {
        document.getElementById("dsDivisionsSelectedTr").style.display = 'none';
    }
    selectList();

}

function removeSelectedRoles() {
    var elSel = document.getElementById('userRolesSelected');
    var i;
    for (i = elSel.length - 1; i >= 0; i--) {
        if (elSel.options[i].selected) {
            elSel.remove(i);
        }
    }
    var count = document.getElementById("userRolesSelected").options.length;
    if (count == 0) {
        document.getElementById("userRolesSelectedTr").style.display = 'none';
    }
    selectRolesList();

}

function addElement() {
    var options = "";
    var dsDivisionName = $("#dsDivision option:selected").text();
    var dsDivisionId = $("select#dsDivision").attr("value");
    var dsDivision = document.getElementById("dsDivision");
    var length = dsDivision.length;
    if (dsDivisionId == 0) {
        for (i = 1; i < length; i++) {
            var val = dsDivision.options[i].value;
            var text = dsDivision.options[i].text;
            if (testDuplicate(val)) {
                options += '<option value="' + val + '">' + text + '</option>';
            }

        }
    } else {
        if (testDuplicate(dsDivisionId)) {
            options = '<option value="' + dsDivisionId + '">' + dsDivisionName + '</option>';
        }

    }
    document.getElementById("dsDivisionsSelectedTr").style.display = 'block';
    $("select#dsDivisionsSelected").append(options);
    selectList();
}

function addRoles() {
    var options = "";
    var roleName = $("#roleId option:selected").text();
    var roleId = $("select#roleId").attr("value");
    var role = document.getElementById("roleId");
    var length = role.length;
    if (roleId == 0) {
        for (i = 1; i < length; i++) {
            var val = role.options[i].value;
            var text = role.options[i].text;
            if (testDuplicateRoles(val)) {
                options += '<option value="' + val + '">' + text + '</option>';
            }

        }
    } else {
        if (testDuplicateRoles(roleId)) {
            options = '<option value="' + roleId + '">' + roleName + '</option>';
        }

    }
    document.getElementById("userRolesSelectedTr").style.display = 'block';
    $("select#userRolesSelected").append(options);
    selectRolesList();
}

function testDuplicate(val) {
    var option = document.getElementById("dsDivisionsSelected").options
    var returnVal = 0;
    if (option.length == 0) {
        returnVal = 0;
        return true;
    }
    for (var x = 0; x < option.length; x++) {
        var val1 = parseInt(option[x].value);
        var val2 = parseInt(val)
        if (val1 == val2) {
            returnVal = 1;
            return false;
        }
    }
    return true;
}

function testDuplicateRoles(val) {
    var option = document.getElementById("userRolesSelected").options
    var returnVal = 0;
    if (option.length == 0) {
        returnVal = 0;
        return true;
    }
    for (var x = 0; x < option.length; x++) {
        var val1 = parseInt(option[x].value);
        var val2 = parseInt(val)
        if (val1 == val2) {
            returnVal = 1;
            return false;
        }
    }
    return true;
}

function isDSUser() {
    var userRole = $("#roleId option:selected").text();

    if (userRole == "ORLM" || userRole == "ORDS" || userRole == "SC") {
        return true;
    } else {
        return false;
    }
}

function isBranchUser() {
    var userRole = $("#roleId option:selected").text();

    if (userRole == "SC") {
        return true;
    } else {
        return false;
    }
}

function isBranchHeadUser() {
    var userRole = $("#roleId option:selected").text();

    if (userRole == "BO" || userRole == "SH") {
        return true;
    } else {
        return false;
    }
}

function isDepartmentUser() {
    var userRole = $("#roleId option:selected").text();

    if (userRole == "SDH" || userRole == "DH") {
        return true;
    } else {
        return false;
    }
}



function showHideAddButton() {
    // var userRole = $("#roleId option:selected").text();
    var role = $("#roleId option:selected").text();
    var userRoleKey = $("#roleId option:selected").val();
    //alert(userRoleKey);

    if (userRoleKey == 0) {
        $("#districtId").hide();
        $("#dsDivisionId").hide();
        $("#add").hide();
        $("#provinceId").hide();

    } else if ( role == "SC" ) {
        $("#districtId").show();
        $("#dsDivisionId").show();
        $("#add").hide();
        $("#provinceId").hide();

    }else if (isDSUser()) {
        $("#districtId").show();
        $("#dsDivisionId").show();
        $("#add").hide();
        $("#provinceId").show();
    } else if (isBranchUser()) {
        $("#districtId").show();
        $("#dsDivisionId").show();
        $("#add").hide();
        $("#provinceId").show();

    }
    else if (isBranchHeadUser()) {
        $("#districtId").hide();
        $("#dsDivisionId").show();
        $("#add").hide();
        $("#provinceId").hide();

    }
    else if (isDepartmentUser()) {
        $("#districtId").hide();
        $("#dsDivisionId").hide();
        $("#add").hide();
        $("#provinceId").hide();

    }
}

function validateData() {

    $("#create-user").validate({
        rules: {
            checkUsername: {
                required: true
            },
            checkFullname: {
                required: true
            },
            checkEmail: {
                required: true,
                email: true
            },
            checkMobile: {
                required: true,
                digits: true,
                minlength: 10
            },
            roleId: {
                selectBox: "default"
            },
            prefLanguage: {
                selectBox: "default"
            }
//                dsDivision:{
//                    selectBox:function(element){
//                        alert(document.getElementById("id").value);
//                       if(document.getElementById("id").value == "LO")
//                       return "notdefault";
//                   }
//                }
        },
        messages: {
            checkUsername: {
                required: "<br>Please enter a username"
            },
            checkFullname: {
                required: "<br>Please enter your full name"
            },
            checkEmail: {
                required: "<br>Please enter your email",
                email: "<br>Please enter a valid email"
            },
            checkMobile: {
                required: "<br>Please enter contact number",
                digits: "<br>Invalid contact number",
                minlength: "<br>Invalid contact number"
            },
            roleId: {
                selectBox: "<br>Please select the Role ID"
            },
            prefLanguage: {
                selectBox: "<br>Please select the Preferred Language"
            }
//                dsDivision:{
//                    selectBox: "Please Select a Ds Division"
//                }
        }
    });

}

</script>

<div id="user-module-home-title" class="module-home-title">
    <s:a href="userModule.do"><img src="${pageContext.request.contextPath}/images/user.png"
                                   alt="User Module"><span><s:label
            value="%{getText('user_module.label')}"/></span></s:a>
    <div id="back-button" align="right">
        <s:submit type="input" value="%{getText('back.label')}" onclick="goBack();"/>
    </div>
</div>
<div id="create-user-div">
<s:if test="editMode==1">
    <h2><s:label value="%{getText('update_user.label')}"/></h2>
</s:if>
<s:else>
    <h2><s:label value="%{getText('create_user.label')}"/></h2>
</s:else>
<hr/>

<s:form id="create-user" name="create-user" method="POST">
<table class="width-100">
<tr>
    <td colspan="2" class="left-align">
        <s:if test="hasActionErrors() || hasActionMessages()">
            <div id="message-box" class="message-box">
                <div class="action-msg"><s:actionmessage/></div>
                <div class="action-err"><s:actionerror/></div>
            </div>
        </s:if>
    </td>
</tr>
<tr>
    <td class="left-align"><s:label value="%{getText('user_name.label')}" cssClass="mandatory-field"/></td>
    <s:if test="editMode==1">
        <td class="left-align"><s:textfield name="registerUser.username" id="checkUsername"
                                            readonly="true" cssClass="width-300-px"/></td>
    </s:if>
    <s:else>
        <td class="right-align"><s:textfield name="registerUser.username" id="checkUsername"
                                             maxLength="50" cssClass="width-300-px"/></td>
    </s:else>
</tr>
<tr>
        <%--<td class="left-align"><s:label value="%{getText('full_name.label')}" cssClass="mandatory-field"/></td>
        <s:if test="editMode==1 and roleId=='SLC'">
            <td class="right-align"><s:textfield name="registerUser.fullName" id="checkFullname"
                                                 readonly="true" cssClass="width-300-px" /></td>
        </s:if>
        <s:else>
            <td class="right-align"><s:textfield name="registerUser.fullName" id="checkFullname"
                                                 cssClass="width-300-px" /></td>
        </s:else>--%>
    <td class="left-align"><s:label value="%{getText('full_name.label')}" cssClass="mandatory-field"/></td>
    <s:if test="editMode==1 and roleId=='SLC'">
        <td class="right-align"><s:textarea name="registerUser.fullName" id="checkFullname"
                                            readonly="true" cssClass="width-300-px" rows="2"/></td>
    </s:if>
    <s:else>
        <td class="right-align"><s:textarea name="registerUser.fullName" id="checkFullname"
                                            cssClass="width-300-px" rows="2"/></td>
    </s:else>

</tr>
<tr>
    <td class="left-align"><s:label value="%{getText('email.label')}" cssClass="mandatory-field"/></td>
    <s:if test="editMode==1 and roleId=='SLC'">
        <td class="right-align"><s:textfield name="registerUser.email" id="checkEmail" maxLength="100"
                                             readonly="true" cssClass="width-300-px"/></td>
    </s:if>
    <s:else>
        <td class="right-align"><s:textfield name="registerUser.email" id="checkEmail" maxLength="100"
                                             cssClass="width-300-px"/></td>
    </s:else>

</tr>
    <%-- Newly added for mobile contact number --%>
<tr>
    <td class="left-align"><s:label value="%{getText('mobile.label')}" cssClass="mandatory-field"/></td>
    <s:if test="editMode==1 and roleId=='SLC'">
        <td class="right-align"><s:textfield name="registerUser.mobile" id="checkMobile" maxLength="10"
                                             readonly="true" cssClass="width-300-px"/></td>
    </s:if>
    <s:else>
        <td class="right-align"><s:textfield name="registerUser.mobile" id="checkMobile" maxLength="10"
                                             cssClass="width-300-px"/></td>
    </s:else>

</tr>

<s:if test="(editMode==1 && (registerUser.loginState.toString() == 'NORMAL' || registerUser.loginState.toString() == 'PASSWORD_RESET')) || (editMode==1 && roleId=='SLC')  ">
    <tr>
        <td class="left-align"><s:label value="%{getText('role_id.label')}"
                                        cssClass="mandatory-field"/></td>
        <td><s:select id="roleId" name="roleId" list="roleSet" headerKey="0"
                      headerValue="%{getText('select.label')}" disabled="true"/></td>
    </tr>
</s:if>
<s:else>
    <tr>
        <td class="left-align"><s:label value="%{getText('role_id.label')}"
                                        cssClass="mandatory-field"/></td>
        <td><s:select id="roleId" name="roleId" list="roleSet" headerKey="0"
                      headerValue="%{getText('select.label')}" onclick="showHideAddButton()"/></td>
    </tr>
</s:else>

    <%-- TODO : do not delete this
   <tr>
       <td colspan="2">
           <input type="button" value="Add" onclick="addRoles()"/>
       </td>
   </tr>
   <tr id="userRolesSelectedTr">
       <td colspan="3">
           <s:select
                   name="userRolesSelected"
                   id="userRolesSelected"
                   list="userRolesSelectedList"
                   multiple="true"
                   />
       </td>

       <td colspan="3">
           <input type="button" value="Delete Selected" onclick="removeSelectedRoles()"/>
       </td>
   </tr> --%>
<tr>
    <td class="left-align"><s:label value="%{getText('user_status.label')}"/></td>
    <s:if test="editMode==1 and roleId=='SLC'">
        <td><s:select id="stateId" name="stateId" list="state" disabled="true"/></td>
    </s:if>
    <s:else>
        <td><s:select id="stateId" name="stateId" list="state"/></td>
    </s:else>
</tr>

    <%--<s:if test="editMode==1 && registerUser.isFirstLogin()==false">

        <tr id="provinceId">
            <td class="left-align"><s:label value="%{getText('province.label')}"/></td>
            <td><s:select list="provinceList" name="province"
                          id="province" headerKey="0" headerValue="%{getText('select.label')}"
                          disabled="true"/></td>
        </tr>

        <tr id="districtId">
            <td class="left-align"><s:label value="%{getText('district.label')}"/></td>
            <td><s:select list="districtList" name="district"
                          id="district" headerKey="0" headerValue="%{getText('select.label')}"
                          disabled="true"/></td>
        </tr>
        <tr id="dsDivisionId">
            <td class="left-align"><s:label value="%{getText('ds_division.label')}"/></td>

            <td><s:select name="dsDivision" id="dsDivision" headerKey="0"
                          headerValue="%{getText('select.label')}"
                          list="dsDivisionList" cssClass="width-180-px" disabled="true"/>

            </td>
        </tr>


    </s:if>
    <s:else>--%>

<tr id="provinceId">
    <td class="left-align"><s:label value="%{getText('province.label')}"/></td>
    <s:if test="editMode==1 and roleId=='SLC'">
        <td><s:select list="provinceList" name="province"
                      id="province" headerKey="0" headerValue="%{getText('select.label')}" disabled="true"/></td>
    </s:if>
    <s:else>
        <td><s:select list="provinceList" name="province"
                      id="province" headerKey="0" headerValue="%{getText('select.label')}"/></td>
    </s:else>
</tr>

<tr id="districtId">
    <td class="left-align"><s:label value="%{getText('district.label')}"/></td>
        <td> <s:select list="districtList" name="assignedDistricts" multiple="true"
                       cssStyle="width:90%;margin-left:0;padding-left:0;"
                       size="10"
                       id="district" value="assignedDistricts" />
        </td>
   <%-- </s:else>
--%>
</tr>
<tr id="dsDivisionId">
    <td class="left-align"><s:label value="Branch"/></td>

    <s:if test="editMode==1 and roleId=='SLC'">
        <td><s:select name="dsDivision" id="dsDivision" headerKey="0"
                      headerValue="%{getText('select.label')}"
                      list="dsDivisionList" cssClass="width-180-px" disabled="true"/>
                <%--</s:else>--%>
        </td>
    </s:if>
    <s:else>
        <td><s:select name="branch" id="branch" headerKey="0"
                      headerValue="%{getText('select.label')}"
                      list="branchList" cssClass="width-180-px"/>
                <%--</s:else>--%>
        </td>
    </s:else>
</tr>
<tr id="add">
    <td colspan="2">
        <s:if test="editMode==1 and roleId=='SLC'">
            <input type="button" id="select_all_col_managers" value="Add" onclick="addElement()" disabled="true"/>
        </s:if>
        <s:else>
            <input type="button" id="select_all_col_managers" value="Add" onclick="addElement()"/>
        </s:else>
    </td>
</tr>
<tr id="dsDivisionsSelectedTr">
    <td colspan="3">
        <s:if test="editMode==1 and roleId=='SLC'">
            <s:select
                    name="dsDivisionsSelected"
                    id="dsDivisionsSelected"
                    list="dsDivisionsSelectedList"
                    multiple="true"
                    disabled="true"
                    />
        </s:if>
        <s:else>
            <s:select
                    name="dsDivisionsSelected"
                    id="dsDivisionsSelected"
                    list="dsDivisionsSelectedList"
                    multiple="true"
                    />
        </s:else>

    </td>

    <td colspan="3">
        <s:if test="editMode==1 and roleId=='SLC'">
            <input type="button" value="Delete Selected" onclick="removeOptionSelected()"
                   id="removeDsButton" disabled="true"/>
        </s:if>
        <s:else>
            <input type="button" value="Delete Selected" onclick="removeOptionSelected()"
                   id="removeDsButton"/>
        </s:else>
    </td>
</tr>

    <%--</s:else>--%>


<tr>
    <td class="left-align"><s:label value="%{getText('preferred_language.label')}"
                                    cssClass="mandatory-field"/></td>
    <td>
        <s:if test="editMode==1 and roleId=='SLC'">
            <s:select
                    list="#@java.util.HashMap@{'si':getText('sinhala.label'),'en':getText('english.label'),'ta':getText('tamil.label')}"
                    name="registerUser.prefLanguage" id="prefLanguage" cssClass="width-180-px" headerKey="0"
                    headerValue="%{getText('select.label')}" disabled="true"/>
        </s:if>
        <s:else>
            <s:select
                    list="#@java.util.HashMap@{'si':getText('sinhala.label'),'en':getText('english.label'),'ta':getText('tamil.label')}"
                    name="registerUser.prefLanguage" id="prefLanguage" cssClass="width-180-px" headerKey="0"
                    headerValue="%{getText('select.label')}"/>
        </s:else>
    </td>
</tr>
<s:if test="editMode==1">

    <tr>
            <%--<td class="left-align"><s:label value="%{getText('reset_password.label')}"/></td>--%>
            <%--<td class="left-align"><s:submit value="%{getText('reset_password.label')}"
            action="resetPassword"/></td>--%>
    </tr>

    <tr>
        <td colspan="2" class="right-align"><s:submit value="%{getText('reset_password.label')}"
                                                      action="resetPassword"/></td>
        <s:if test="roleId!='SLC'">
            <td colspan="2" class="right-align"><s:submit value="%{getText('update.label')}"
                                                          action="updateUser" onclick="validateData()"/></td>
        </s:if>
    </tr>
</s:if>
<s:else>
    <tr>
        <td colspan="2" class="right-align"><s:submit value="%{getText('save.label')}"
                                                      action="createUser" onclick="validateData()"/></td>
    </tr>
</s:else>
</table>
</s:form>
</div>

<s:hidden name="registerUser.username"/>
<s:hidden id="edit_mode" name="editMode"/>
<%-- <s:hidden id="userRoleMode" name="userRoleMode"/> --%>
<s:hidden id="userSelected" name="roleId"/>
<s:hidden id="assignedDistrictsId" name="assignedDistricts"/>


